/*
 * COPYRIGHT. ShenZhen JiMi Technology Co., Ltd. 2017.
 * ALL RIGHTS RESERVED.
 *
 * No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
 * on any form or by any means, electronic, mechanical, photocopying, recording, 
 * or otherwise, without the prior written permission of ShenZhen JiMi Network Technology Co., Ltd.
 *
 * Amendment History:
 * 
 * Date                   By              Description
 * -------------------    -----------     -------------------------------------------
 * 2017年6月29日    Li.Shangzhi         Create the class
 * http://www.jimilab.com/
 */

package com.jimi.framework.base;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @FileName BaseController.java
 * @Description:
 *
 * @Date 2017年6月29日 上午10:56:53
 * @author Li.Shangzhi
 * @version 1.0
 */
public class BaseController {

	protected final Logger logger = LoggerFactory.getLogger(super.getClass().getName());

	/**
	 * @Title: getAccessToken
	 * @Description: 获取授权的令牌
	 * @param request
	 * @return
	 * @author Li.Shangzhi
	 * @date 2017年6月29日 上午11:04:24
	 */
	public String getAccessToken(HttpServletRequest request) {
		return request.getParameter("accessToken");
	}
	
	/**
	 * @Title: getParamValues 
	 * @Description:从request中获取参数根据键值对形成Map. <br>
	 * 注意:对于数组参数，只拷贝了第1个元素.<br>
	 * 对于全空格的数据，仍然保留，在保存修改时可能需要.
	 * @param request
	 * @return 
	 * @author Li.Shangzhi
	 * @date 2017年6月29日 下午8:40:14
	 */
	public Map<String, Object> getParamValues(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		@SuppressWarnings("rawtypes")
		Enumeration names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String key = (String) names.nextElement();
			String value = request.getParameter(key);
			if (value != null && !"".equals(value)) {
				map.put(key, value);
			}
		}
		return map;
	}
	
	/**
	 * @Title: flushResponse 
	 * @Description:
	 * @param response
	 * @param responseContent 
	 * @author Li.Shangzhi
	 * @date 2017年6月29日 下午8:42:33
	 */
	public void flushResponse(HttpServletResponse response, String responseContent) {
		response.setCharacterEncoding("UTF-8");
		String contentType = "application/json; charset=UTF-8";
		response.setContentType(contentType);
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.write(responseContent);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			writer.flush();
			writer.close();
		}
	}
}
